package com.sqllog.admin.sql.datasource;

import com.alibaba.fastjson.JSON;
import com.mongodb.*;
import com.mongodb.client.*;
import com.mongodb.client.MongoClient;
import com.mongodb.client.model.IndexOptions;
import com.mongodb.client.model.Indexes;
import com.sqllog.admin.sql.domain.DatasourceMemoryInfo;
import com.sqllog.admin.sql.domain.QueryParamInfo;
import com.sqllog.admin.sql.domain.ReturnDataInfo;
import com.sqllog.admin.sql.domain.SqlLogInfo;
import com.sqllog.admin.utils.CommonUtils;
import org.bson.BsonDocument;
import org.bson.Document;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.conversions.Bson;
import org.springframework.data.mongodb.MongoDatabaseUtils;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * mongoDB 保存
 *
 * @author chennengcheng
 * @date 2022-01-04 15:57
 * @remark
 */

@Component
public class MongoDbSaveDataSourceOption implements LogSaveDataSourceOption {

    private MongoTemplate mongoTemplate;

    private MongoClient mongoClient;

    private static Mongo mongo;

    private static DB db;

    public MongoDbSaveDataSourceOption(MongoTemplate mongoTemplate, MongoClient mongoClient) {
        this.mongoTemplate = mongoTemplate;
    }

    @Override
    public DatasourceMemoryInfo getDatasourceMemoryUsed(){
        MongoDatabase db = mongoTemplate.getDb();
        Document document = db.runCommand(new Document("dbStats", null));
        System.out.println("storageSize: " + document.toJson());
        // 已占用内存
        BigDecimal storageSize = new BigDecimal(String.valueOf(document.get("storageSize")));
        // 总占用内存
        BigDecimal fsTotalSize =  new BigDecimal(String.valueOf(document.get("fsTotalSize")));
        // 总集合数
        int collections =  (int) document.get("collections");
        // 总记录数
        int rowNum =  (int) document.get("objects");

        DatasourceMemoryInfo datasourceMemoryInfo = new DatasourceMemoryInfo();
        CommonUtils.MemoryUnitInfo fsTotalSizeData = CommonUtils.getPrintSize(fsTotalSize.longValue());
        datasourceMemoryInfo.setTotalMemory(fsTotalSizeData.getData());
        datasourceMemoryInfo.setTotalMemoryUnit(fsTotalSizeData.getUnit());
        CommonUtils.MemoryUnitInfo storageSizeData = CommonUtils.getPrintSize(storageSize.longValue());
        datasourceMemoryInfo.setUsedMemory(storageSizeData.getData());
        datasourceMemoryInfo.setUsedMemoryUnit(storageSizeData.getUnit());
        datasourceMemoryInfo.setTotalRowNum(new BigDecimal(rowNum).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_HALF_DOWN));
        datasourceMemoryInfo.setTotalTableNum(new BigDecimal(collections));
        return datasourceMemoryInfo;
    }



    // DateUtil.format(new Date(), "yyyy-MM")
    @Override
    public void createTable(String dataBaseName, String tableName, String month) {
        String collectionName = CommonUtils.generateTableNameByYearOfMonth(dataBaseName, tableName, month);
        mongoTemplate.createCollection(collectionName);
    }

    @Override
    public boolean checkExistsTableName(String dataBaseName, String tableName, String month) {
        String collectionName = CommonUtils.generateTableNameByYearOfMonth(dataBaseName, tableName, month);
        return mongoTemplate.collectionExists(collectionName);
    }

    @Override
    public void deleteTable(String dataBaseName, String tableName, String month) {
        String collectionName = CommonUtils.generateTableNameByYearOfMonth(dataBaseName, tableName, month);
        mongoTemplate.dropCollection(collectionName);
    }

    @Override
    public void createTableIndex(String dataBaseName, String tableName, String month, String indexFiledName) {
        String collectionName = CommonUtils.generateTableNameByYearOfMonth(dataBaseName, tableName, month);
        //配置索引选项
        IndexOptions options = new IndexOptions();
        // 后台创建索引
        options.background(true);
        //创建按filedName升序排的索引
        MongoCollection<Document> collection = mongoTemplate.getCollection(collectionName);
        collection.createIndex(Indexes.ascending(indexFiledName), options);
    }

    @Override
    public int insert(String dataBaseName, String tableName, String month, List<SqlLogInfo> sqlLogInfos) {
        String collectionName = CommonUtils.generateTableNameByYearOfMonth(dataBaseName, tableName, month);
        Collection<Object> result = mongoTemplate.insert(sqlLogInfos, collectionName);
        return result.size();
    }

    @Override
    public List<ReturnDataInfo> list(QueryParamInfo queryParamInfo) {
//        List<ReturnDataInfo> sqlLogVos = mongoTemplate.find(query, ReturnDataInfo.class, sqlLogDto.getCollectionName());

        return new ArrayList<>();
    }

    @Override
    public long countRecordNum(QueryParamInfo queryParamInfo) {
        return 0;
    }

    @Override
    public ReturnDataInfo getById(QueryParamInfo queryParamInfo) {
        return null;
    }

}
